package SocketBaseTest;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by yexuan on 2018/3/24.
 * 上传图片
 */
public class PicClient {
    public static void main(String[] args) throws Exception{
        Socket s = new Socket("172.16.35.23",10004);
        FileInputStream fis = new FileInputStream("test1.jpg");
        OutputStream os = s.getOutputStream();

        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = fis.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        s.shutdownOutput();

        InputStream is = s.getInputStream();
        byte[] b = new byte[1024];
        System.out.println(new String(b,0,is.read(b)));

        fis.close();
        s.close();

    }
}

class PicServer{
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(10004);
        while (true){
            Socket s = ss.accept();
            new Thread(new server(s)).start();
        }
    }
}

class server implements Runnable{
    private Socket s;

    public server(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip + ".....connect");
        try {
            InputStream is = s.getInputStream();
            FileOutputStream fos = new FileOutputStream("tcpPic"+System.currentTimeMillis()+".jpg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes))!=-1){
                fos.write(bytes,0,len);
            }

            OutputStream os = s.getOutputStream();
            os.write("上传成功".getBytes());

            fos.close();
            s.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}